library _;

import 'dart:convert';
import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_yfree/YFree.dart';
import 'package:flutter_yim/YIM.dart';
import 'package:pc/Const/IFinal.dart';
import 'package:pc/Extension/String++.dart';
import 'package:pc/Extension/special_text/emoji_text.dart';
import 'package:pc/Extension/special_text/my_special_text_span_builder.dart';
import 'package:pc/Model/Enums.dart';
import 'package:pc/Model/MessageModel.dart';
import 'package:pc/Page/Home/Chat/controller.dart';
import 'package:pc/Page/Other/ShowVideo/main.dart';
import 'package:pc/Util/WindowUtils.dart';
import 'package:pc/Util/YOSS/YOSS.dart';
import 'package:pc/View/ChatFaceButton.dart';
import 'package:pc/View/ChatFileButton.dart';
import 'package:pc/View/ChatRecordMsg.dart';
import 'package:pc/View/ChatScreenshotButton.dart';

part 'extensions/MessageGesture.dart';

part 'extensions/MessageView.dart';

class ChatView {
  final page = IFinal.Others.homePage;

  Widget chat() {
    Widget view_pullLoading() {
      if (!page.controller_chat!.state.isRefreshing) return YEmpty();
      return Card(
        margin: EdgeInsets.only(top: 10),
        elevation: 5,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(99)),
        child: Container(
          width: 30,
          height: 30,
          child: CircularProgressIndicator(strokeWidth: 3, backgroundColor: Colors.grey.shade200),
        ),
      );
    }

    Widget view_top() {
      return Container(
        color: Color.fromARGB(255, 241, 241, 241),
        padding: EdgeInsets.fromLTRB(20, 14, 20, 14),
        child: Row(
          children: [
            Text(page.controller_conversation!.getSelectConversation()!.name, style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
            YExpanded(),
            YButton(
              isInk: true,
              child: Icon(Icons.more_horiz_rounded),
              onTap: () => page.controller_chat!.showSlidingMenu(),
            ),
          ],
        ),
      );
    }

    Widget view_function() {
      return Container(
        color: Color.fromARGB(255, 241, 241, 241),
        padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
        child: Row(
          children: [
            ChatFaceButton(
              onFaceTap: (index) {
                final face = "[emoticon_${index + 1}]";
                final cursorIndex = page.controller_chat!.state.textEditingController.selection.baseOffset;
                if (cursorIndex < 0) {
                  page.controller_chat!.state.textEditingController.text = face;
                  page.controller_chat!.state.textEditingController.selection = TextSelection.fromPosition(TextPosition(offset: face.length));
                  return;
                }
                if (cursorIndex == 0) {
                  page.controller_chat!.state.textEditingController.text = "$face${page.controller_chat!.state.textEditingController.text.substring(cursorIndex, page.controller_chat!.state.textEditingController.text.length)}";
                  page.controller_chat!.state.textEditingController.selection = TextSelection.fromPosition(TextPosition(offset: cursorIndex + face.length));
                  return;
                }
                page.controller_chat!.state.textEditingController.text = "${page.controller_chat!.state.textEditingController.text.substring(0, cursorIndex)}$face${page.controller_chat!.state.textEditingController.text.substring(cursorIndex, page.controller_chat!.state.textEditingController.text.length)}";
                page.controller_chat!.state.textEditingController.selection = TextSelection.fromPosition(TextPosition(offset: cursorIndex + face.length));
              },
              onDeleteTap: () {
                final cursorIndex = page.controller_chat!.state.textEditingController.selection.baseOffset;
                if (cursorIndex <= 0) return;
                if (cursorIndex <= 1) {
                  page.controller_chat!.state.textEditingController.text = "${page.controller_chat!.state.textEditingController.text.substring(cursorIndex, page.controller_chat!.state.textEditingController.text.length)}";
                  page.controller_chat!.state.textEditingController.selection = TextSelection.fromPosition(TextPosition(offset: 0));
                  return;
                }
                final curChar = page.controller_chat!.state.textEditingController.text.characters.getRange(cursorIndex - 1, cursorIndex).string;
                if (curChar != "]" || !page.controller_chat!.state.textEditingController.text.substring(0, cursorIndex - 1).contains(EmojiText.prefix)) {
                  page.controller_chat!.state.textEditingController.text = "${page.controller_chat!.state.textEditingController.text.substring(0, cursorIndex - 1)}${page.controller_chat!.state.textEditingController.text.substring(cursorIndex, page.controller_chat!.state.textEditingController.text.length)}";
                  page.controller_chat!.state.textEditingController.selection = TextSelection.fromPosition(TextPosition(offset: cursorIndex - 1));
                  return;
                }
                final emojiStartIndex = page.controller_chat!.state.textEditingController.text.substring(0, cursorIndex - 1).lastIndexOf(EmojiText.prefix);
                page.controller_chat!.state.textEditingController.text = "${page.controller_chat!.state.textEditingController.text.substring(0, emojiStartIndex)}${page.controller_chat!.state.textEditingController.text.substring(cursorIndex, page.controller_chat!.state.textEditingController.text.length)}";
                page.controller_chat!.state.textEditingController.selection = TextSelection.fromPosition(TextPosition(offset: emojiStartIndex));
                page.setState(() {});
              },
            ),
            YSpacer(width: 15),
            ChatFileButton(
              fileType: FileType.Image,
              onSelectFiles: (files) => page.controller_chat!.upload(files, FileType.Image),
            ),
            YSpacer(width: 15),
            ChatFileButton(
              fileType: FileType.Video,
              onSelectFiles: (files) => page.controller_chat!.upload(files, FileType.Video),
            ),
            YSpacer(width: 15),
            ChatScreenshotButton(
              onCapture: (file) => page.controller_chat!.upload([XFile(file!)], FileType.Image),
            ),
          ],
        ),
      );
    }

    Widget view_input() {
      return DropTarget(
        onDragEntered: (details) {
          page.setState(() => page.controller_chat!.state.isDragingFile = true);
        },
        onDragExited: (details) {
          page.setState(() => page.controller_chat!.state.isDragingFile = false);
        },
        onDragDone: (details) {
          details.files.forEach((file) {
            if (["jpg", "png", "gif"].contains(file.path.split(".").last.toLowerCase())) {
              page.controller_chat!.upload([file], FileType.Image);
            }
            if (["mp4"].contains(file.path.split(".").last.toLowerCase())) {
              page.controller_chat!.upload([file], FileType.Video);
            }
          });
        },
        child: Container(
          height: 150,
          decoration: BoxDecoration(
            color: Color.fromARGB(255, 240, 240, 240),
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: (page.controller_chat?.state.isDragingFile ?? false) ? YConfig.themeColor : Colors.transparent, width: 2),
          ),
          margin: EdgeInsets.all(5),
          alignment: Alignment.centerLeft,
          child: Scrollbar(
            child: KeyboardListener(
              focusNode: FocusNode(),
              child: ExtendedTextField(
                controller: page.controller_chat!.state.textEditingController,
                focusNode: page.controller_chat!.state.focusNode,
                maxLines: 999,
                style: TextStyle(fontSize: 14, height: 1.4),
                cursorWidth: 1,
                cursorHeight: 14,
                specialTextSpanBuilder: mySpecialTextSpanBuilder,
                decoration: InputDecoration(isCollapsed: true, contentPadding: EdgeInsets.all(5), border: InputBorder.none),
                onChanged: (value) => page.setState(() {}),
              ),
              onKeyEvent: (event) {
                if (event.physicalKey == PhysicalKeyboardKey.enter) {
                  final content = page.controller_chat!.state.textEditingController.text;
                  if (content.trim().isEmpty) {
                    page.controller_chat!.state.textEditingController.clear();
                    return;
                  }
                  page.controller_chat!.sendMessage(
                    Enum_MessageType.Text,
                    content,
                    onSendStart: (yimMessage) {
                      page.controller_chat!.state.textEditingController.clear();
                      page.controller_chat!.addMessages(messages: [MessageModel.fromYIMMessage(yimMessage, true)]);
                      page.controller_chat!.scrollToBottom();
                    },
                  );
                }
              },
            ),
          ),
        ),
      );
    }

    Widget view_message() {
      return ListView.builder(
        controller: page.controller_chat!.state.scrollController,
        reverse: true,
        primary: false,
        shrinkWrap: true,
        padding: EdgeInsets.only(top: 10),
        itemCount: page.controller_chat!.state.messages.length,
        itemBuilder: (context, index) {
          return Container(
            width: 200,
            padding: EdgeInsets.fromLTRB(10, 0, 10, 20),
            child: message_list(page.controller_chat!.state.messages[index]),
          );
        },
      );
    }

    return Container(
      color: Color.fromARGB(255, 241, 241, 241),
      child: page.controller_chat!.state.messages.isEmpty || page.controller_conversation!.getSelectConversation() == null
          ? Center(child: Image.asset("images/bg_empty_message.png", width: 300))
          : Column(
              children: [
                view_top(),
                Container(height: 0.05, color: Colors.black),
                Expanded(
                  child: Stack(
                    alignment: Alignment.topCenter,
                    children: [
                      view_message(),
                      Positioned(top: 0, child: view_pullLoading()),
                    ],
                  ),
                ),
                Container(height: 0.05, color: Colors.black),
                view_function(),
                view_input(),
              ],
            ),
    );
  }
}
